<template>
  <view class="container">
    <view v-for="item in lists" :key="item.id">
      <view class="post">
        <view class="post-header">
          <!-- 头像 -->
          <image :src="fileUrl + item.avatar" class="avatar"></image>
          <!-- 个人信息 -->
          <view class="user-info">
            <view class="user-header">
              <text class="user-name">{{ item.username }}</text>
              <image :src="item.gender == 'F' ? '/static/images/female.png' : '/static/images/male.png'"
                class="gender-icon"></image>
            </view>
            <text class="user-details">{{ item.my_city }} · {{ item.age }}岁 · {{ item.height }}cm ·
              {{ item.education }}</text>
          </view>
        </view>
        <view class="post-content">
          <view class="post-text">
            <text>{{ item.content }}</text>
          </view>
          <image v-for="(img, index) in item.image" :src="fileUrl + img" :key="img" mode="widthFix" class="post-image"
            @click="() => {
              Previews(item.image, index)
            }
              "></image>
          <!-- <image src="/static/images/post.png" mode="widthFix" class="post-image"></image> -->
        </view>

        <view class="post-footer">
          <!-- 点赞 -->
          <view class="inter-like" style="border: 1.5px solid #ef8474">
            <image :src="thumblist!.includes(item.id) ? '/static/Meet/isthumb.png' : '/static/Meet/thumb.png'"
              class="thumb-icon" @tap="thumb(item.id)"></image>
            <text>点赞</text>
          </view>

          <!-- 喜欢 -->
          <view class="inter-like" @tap="like(item.user_id)" style="border: 1.5px solid #ea6389">
            <image :src="likelist.includes(item.user_id)
              ? '/static/Meet/like.png'
              : '/static/Meet/islike.png'
              " class="like-icon"></image>
            <text>喜欢</text>
          </view>

          <!-- 送礼 -->
          <view @tap="showGiftPopup(item.id, item.user_id)" class="inter-like" style="border: 1.5px solid #f0b74c">
            <image src="/static/Meet/gift.png" class="thumb-icon" style="margin-left: 15rpx" />
            <text>礼物</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 送礼弹框 -->
    <uni-popup ref="popup" type="bottom">
      <view class="popup-content">
        <view class="gift" v-for="(gift, index) in gifts" :key="index"
          @tap="selectGift(gift.video, index, gift.name, gift.id)" :class="{ selected: selectedGiftIndex === index }">
          <image :src="gift.url" class="gift-icon" />
          <view class="gift-money">
            <text style="font-size: 30rpx">10</text>
            <image src="/static/Meet/coin.png" class=".gift-coin" />
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 礼物视频展示 -->
    <view v-show="selectedGift" class="video-container">
      <video ref="giftVideo" :src="selectedGift" object-fit="fill" :autoplay="true" :controls="false"
        :enable-progress-gesture="false" :loop="false" style="width: 676rpx; height: 676rpx; object-fit: cover"
        class="video-container-video" @loadedmetadata="onVideoLoaded" @ended="onVideoEnded"></video>
    </view>
    <Preview :images="imageList" :fileUrl="fileUrl" :flag="isFlag" :close="() => {
      isFlag = false
    }
      " :index="imageIndex"></Preview>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineProps } from 'vue'
import type { UniPopup } from '@uni-helper/uni-ui-types/index'
import { Preview } from '@/components/Preview/index.vue'
import {
  getGiftItemApi,
  getBlogItemApi,
  thumbBlogItemApi,
  getCoinItemApi,
  getThumbBlogApi,
  getLikeBlogApi,
  likeBlogItemApi,
  postGiftItemApi,
} from '@/services/index/home'
import type { blogItem, giftItem } from '@/types/index/home'

// 从本地存储获取用户id
const userId = ref('')
const token = ref('')
const imageList = ref([])
const isFlag = ref(false)
const imageIndex = ref(0)
const Previews = (image: any, index: number) => {
  imageList.value = image
  isFlag.value = true
  imageIndex.value = index
}
let { lists, fileUrl, page } = defineProps(['lists', 'fileUrl', 'page'])
// 获取动态
onMounted(() => {
  const userInfo = uni.getStorageSync('userInfo')
  userId.value = userInfo.id
  token.value = userInfo.token
  getGift()
  getThumbBloglist()
  getLikeBlog()
  // 获取金币
  getCoin()
})

// 用户id
// const userId = ref("c61a8166-6a49-42ba-8173-39babe2c8d8f")
const active = ref(0)
const selectedGiftIndex = ref<number | null>(null)
const selectedGift = ref('')
const videoDuration = ref(0) // 新增：视频时长
const popup = ref<UniPopup | null>(null)
const giftVideo = ref<HTMLVideoElement | null>(null)
const usercoin = ref<number>(0)
const blog = ref('')
const senduser = ref('')

// 获取金币
const getCoin = () => {
  getCoinItemApi(userId.value).then((res) => {
    usercoin.value = res.money
  })
}

// 礼物列表
const gifts = ref<giftItem[]>([])

// 获取礼物
const getGift = () => {
  getGiftItemApi().then((res) => {
    // console.log(res)
    gifts.value = res.data.result.send
  })
}

// 点赞列表
const thumblist = ref<string[]>([])

// 喜欢列表
const likelist = ref<string[]>([])

// 点赞

// 获取点赞表

const getThumbBloglist = async () => {
  await getThumbBlogApi(userId.value).then((res) => {
    // console.log(res, '获取点赞表')
    thumblist.value = res.data.result
  })
}

// 点击点赞
const thumb = async (postid: string) => {
  console.log('234523556')
  if (!token.value) {
    console.log('111')
    uni.showToast({
      title: '请先登录',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login',
      })
    }, 1500)
  } else {
    const pararm = {
      user_id: userId.value,
      blog_id: postid,
    }
    await thumbBlogItemApi(pararm).then((res) => {
      console.log(res, '点赞')
    })
    getThumbBloglist()
  }
}

// 获取喜欢列表
const getLikeBlog = async () => {
  await getLikeBlogApi(userId.value).then((res) => {
    console.log(res, '获取喜欢表')
    likelist.value = res.data.list_your_id
    setTimeout(() => {
      console.log(likelist.value, '喜欢表')
    }, 5000)
  })
}

// 点击喜欢

const like = (user_id_your: string) => {
  if (!token.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login',
      })
    }, 1500)
  } else {
    const pararm = {
      user_id_my: userId.value,
      user_id_your: user_id_your,
    }
    likeBlogItemApi(pararm).then((res) => {
      console.log(res, '喜欢')
    })
    getLikeBlog()
  }
}

// const active = ref("0")

// 最新
onMounted(async () => {
  uni.$on('active0', (msg) => {
    active.value = msg
    getBlogItemApi(page).then((res) => {
      console.log(res, '5555555');
      lists = res?.data?.result || []
    })
  })
})

// 最热
onMounted(() => {
  // 监听全局事件并直接接收值
  uni.$on('active1', (msg) => {
    active.value = msg
  })
})

watch(active, (newValue, oldValue) => {
  if (active.value === '1') {
    // 根据点赞排序
    lists.value = lists.value.sort((a, b) => {
      return b.like_num - a.like_num // 注意顺序，b - a 是降序
    })
  }
})

// 打开礼物弹窗
const showGiftPopup = (blog_id: string, send_user: string) => {
  if (!token.value) {
    console.log('111')
    uni.showToast({
      title: '请先登录',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login',
      })
    }, 1500)
  } else {
    ; (popup.value as UniPopup).open()
    blog.value = blog_id
    senduser.value = send_user
  }
}

const selectGift = async (gift: any, index: number, giftsname: string, giftid: string) => {
  console.log(giftid, '0000');

  selectedGiftIndex.value = index
  if (usercoin.value >= 10) {
    const pararm = {
      id: userId.value,
      blog: blog.value,
      gifts: giftid,
      send_user: senduser.value,
      gift_name: giftsname,
    }

    await postGiftItemApi(pararm).then((res) => {
      console.log(res, '1111')
      getCoin()
    })
    selectedGift.value = gift
  } else {
    uni.showToast({
      title: '金币不足',
      icon: 'none',
    })
  }
}

// 函数：视频元数据加载完成时调用，获取视频时长
const onVideoLoaded = () => {
  if (giftVideo.value) {
    videoDuration.value = giftVideo.value.duration
    // console.log('视频时长:', videoDuration.value, '秒')
    // 设置定时器在视频播放完毕后关闭弹窗
    setTimeout(() => {
      selectedGift.value = '' // 修改: 使用 null
      // (popup.value as UniPopup).close()
    }, videoDuration.value * 1000)
  }
}

// 函数：视频播放结束时调用
const onVideoEnded = () => {
  selectedGift.value = '' // 修改: 使用 null
  // (popup.value as UniPopup).close()
}
</script>

<style scoped>
/* 头部 */

/* 动态 */
.container {
  margin-top: 60rpx;
  /* padding: 10px; */
  width: 100%;
  height: 100vh;
}

.post {
  padding: 20px 10px;
  margin-bottom: 10px;
  border-radius: 20px;
  border: 1px solid #f1ebeb;
  box-shadow: 2rpx 5rpx 10rpx -2rpx #dbdbdb;
}

.post-header {
  display: flex;
  align-items: start;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 10px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-header {
  display: flex;
  align-items: center;
}

.user-name {
  font-weight: bold;
}

.gender-icon {
  width: 30rpx;
  height: 30rpx;
  margin-left: 5px;
}

.like-icon {
  width: 30rpx;
  height: 30rpx;
  margin-left: 5px;
}

.user-details {
  color: #888;
  font-size: 12px;
}

.post-content {
  margin-left: 60rpx;
  margin-top: 10rpx;
}

.post-content image {
  margin-top: 10px;
  width: 90%;
  border-radius: 15px;
}

.post-text {
  margin-top: 15px;
}

.post-footer {
  width: 85%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  margin-left: 22px;
}

.thumb-icon {
  width: 40rpx;
  height: 40rpx;
}

.inter-like {
  padding: 10rpx;
  width: 150rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 20px;
  border: 1px solid rgb(186, 181, 181);
}

/* 返回顶部 */
.back-to-top-icon {
  position: fixed;
  bottom: 50rpx;
  right: 20rpx;
  width: 70rpx;
  height: 70rpx;
}

/* 发布按钮 */
.send {
  position: fixed;
  bottom: 50rpx;
  left: calc(100vw - 50vw);
  width: 70rpx;
  height: 70rpx;
}

.popup-content {
  display: flex;
  flex-wrap: wrap;
  padding: 40rpx;
  width: 100vw;
  height: 25vh;
  display: inline-flex;
  justify-content: space-around;
  border: 1rpx solid #d6cfcf;
  border-radius: 10rpx;
  /* box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1); */
  background-color: white;
}

/* 礼物 */
.gift {
  /* background-color: #bb1b1b; */
  padding: 10rpx;
  border: 1rpx solid transparent;
  cursor: pointer;
  margin-top: 30rpx;
}

.gift-money {
  margin-top: 30rpx;
  display: flex;
  justify-content: center;
}

.gift-icon {
  width: 110rpx;
  height: 110rpx;
}

/* 金币 */
.gift-coin {
  width: 50rpx;
  height: 50rpx;
}

.gift.selected {
  border-color: rgb(196, 196, 209);
}

.video-container {
  width: 100%;
  height: 47vh;
  position: sticky;
  bottom: 36vh;
  left: 0;
  right: 0;
  top: 1vh;
  /* margin: auto; */
  z-index: 999;
  /* background-color: pink; */
  text-align: center;
  animation: shink 1s;
}

.video-container-video {
  width: 100%;
  height: 100%;
  animation: shink 1s;
}

@keyframes shink {
  0% {
    width: 0%;
    height: 0%;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  100% {
    width: 100%;
    height: 47vh;
    left: 0;
    top: 1vh;
  }
}

/* 送礼的弹框 */

.confirm-content {
  width: 500rpx;
  height: 250rpx;
  background-color: white;
  padding: 30rpx;
  text-align: center;
  border-radius: 15rpx;
  box-sizing: border-box;
}

.confirm-content text {
  padding-top: 15rpx;
  font-size: 35rpx;
}

.button-group {
  display: flex;
  justify-content: space-around;
  margin-top: 20rpx;
}

.button-group button {
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  border: none;
  border-radius: 10rpx;
}

/* 取消按钮 */
.button-group button:first-child {
  margin-top: 15rpx;
  width: 100px;
  height: 80rpx;
  line-height: 60rpx;
  background-color: #f8f6f6;
  font-size: 30rpx;
}

/* 确认按钮 */
.button-group button:last-child {
  margin-top: 15rpx;
  width: 100px;
  height: 80rpx;
  line-height: 60rpx;
  background-color: #0f84d8;
  color: white;
  font-size: 30rpx;
}
</style>
